package com.mj.mafeed.activity;

import java.util.List;

import com.mj.mafeed.R;
import com.mj.mafeed.bean.CartItemJSON;
import com.mj.mafeed.bean.CartItemListJSON;
import com.mj.mafeed.bean.OrderJSON;
import com.mj.mafeed.bean.PaymentMethodJSON;
import com.mj.mafeed.bean.ReceiverJSON;
import com.mj.mafeed.bean.ShippingMethodJSON;
import com.mj.mafeed.service.CartItemService;
import com.mj.mafeed.service.OrderService;
import com.mj.mafeed.service.PaymentMethodService;
import com.mj.mafeed.service.ReceiverService;
import com.mj.mafeed.service.ShippingMethodService;
import com.mj.mafeed.util.NetUtils;
import com.mj.mafeed.util.SPUtils;
import com.mj.mafeed.widget.LoadingDialog;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 结算
 * @author zhaominglei
 * @date 2014-12-23
 * 
 */
public class CheckoutActivity extends Activity implements OnClickListener {
	@SuppressWarnings("unused")
	private static final String TAG = CheckoutActivity.class.getSimpleName();
	private PaymentMethodService paymentMethodService = new PaymentMethodService();
	private ShippingMethodService shippingMethodService = new ShippingMethodService();
	private CartItemService cartItemService = new CartItemService();
	private OrderService orderService = new OrderService();
	
	private ImageView goHome;
	private ImageView receiverSelect; //收货地址选择
	private TextView receivernoneText;
	private ImageView consigneePrefix;
	private TextView consigneeText;
	private ImageView phonePrefix;
	private TextView phoneText;
	private TextView addressText;
	private TextView zipCodeText;
	private RadioGroup pmRadioGroup; //支付方式
	private RadioGroup smRadioGroup; //配送方式
	private CheckBox invoiceBox;
	private TextView invoiceTitle;
	private EditText invoiceText;
	private TextView totalText;
	private Button checkoutBtn;
	private String referer; //来自那个链接
	private String username; //用户名
	private String sign; //签名
	private LoadingDialog loadingDialog; //加载框
	private double total = 0.0d; //总计金额
	private Intent intent;
	private CartItemListJSON cartItemListJSON;
	private ReceiverJSON receiver;
	private boolean isInvoice = false; //是否需要发票
	private String invoiceinfo; //发票抬头
	private Long receiverId; //收货地址id
	private Long paymentMethodId; //支付方式id
	private Long shippingMethodId; //配送方式id
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_checkout);
		
		init();
	}
	
	private void init() {
		goHome = (ImageView)findViewById(R.id.checkout_gohome);
		receiverSelect = (ImageView)findViewById(R.id.checkout_receiver_select);
		receivernoneText = (TextView)findViewById(R.id.checkout_receiver_none_hint);
		consigneePrefix = (ImageView)findViewById(R.id.checkout_receiver_template_consignee_prefix);
		consigneeText = (TextView)findViewById(R.id.checkout_receiver_template_consignee);
		phonePrefix = (ImageView)findViewById(R.id.checkout_receiver_template_phone_prefix);
		phoneText = (TextView)findViewById(R.id.checkout_receiver_template_phone);
		addressText = (TextView)findViewById(R.id.checkout_receiver_template_address);
		zipCodeText = (TextView)findViewById(R.id.checkout_receiver_template_zipCode);
		//初始化支付方式
		pmRadioGroup = (RadioGroup)findViewById(R.id.checkout_paymentmethod);
		List<PaymentMethodJSON> paymentMethods = paymentMethodService.getAll(this);
		for (int i = 0; (paymentMethods != null && paymentMethods.size() > 0) && i < paymentMethods.size(); i++) {
			PaymentMethodJSON paymentMethodJSON = paymentMethods.get(i);
			RadioButton radioButton = new RadioButton(this);
			radioButton.setId(paymentMethodJSON.getPaymentMethodId().intValue());
			radioButton.setText(paymentMethodJSON.getName());
			radioButton.setTextColor(Color.BLACK);
			if (i == (paymentMethods.size() -1) && paymentMethods.size() == 1) {
				radioButton.setChecked(true);
			}
			pmRadioGroup.addView(radioButton);
		}
		//初始化配送方式
		smRadioGroup = (RadioGroup)findViewById(R.id.checkout_shippingmethod);
		List<ShippingMethodJSON> shippingMethods = shippingMethodService.getAll(this);
		for (int i = 0; (shippingMethods != null && shippingMethods.size() > 0) && i < shippingMethods.size(); i++) {
			ShippingMethodJSON shippingMethodJSON = shippingMethods.get(i);
			RadioButton radioButton = new RadioButton(this);
			radioButton.setId(shippingMethodJSON.getShippingMethodId().intValue());
			radioButton.setText(shippingMethodJSON.getName());
			radioButton.setTextColor(Color.BLACK);
			if (i == (shippingMethods.size() -1) && shippingMethods.size() == 1) {
				radioButton.setChecked(true);
			}
			smRadioGroup.addView(radioButton);
		}
		invoiceBox = (CheckBox)findViewById(R.id.checkout_invoice);
		invoiceTitle = (TextView)findViewById(R.id.checkout_invoice_title_title);
		invoiceText = (EditText)findViewById(R.id.checkout_invoice_title_value);
		totalText = (TextView)findViewById(R.id.checkout_total);
		checkoutBtn = (Button)findViewById(R.id.checkout_submit);
		
		goHome.setOnClickListener(this);
		receiverSelect.setOnClickListener(this);
		invoiceBox.setOnClickListener(this);
		checkoutBtn.setOnClickListener(this);
		loadingDialog = new LoadingDialog(this);
		
		invoiceTitle.setVisibility(View.INVISIBLE);
		invoiceText.setVisibility(View.INVISIBLE);
		referer = getIntent().getStringExtra("referer");
		username = (String)SPUtils.get(getApplicationContext(), "username", "");
		sign = (String)SPUtils.get(getApplicationContext(), "sign", "");
		if (referer != null && referer.equals("CartActivity")) {
			total = getIntent().getDoubleExtra("total", 0.0d);
			getdefaultReceiver();
		} else if (referer != null && referer.equals("ReceiverSelectActivity")) {
			receiver = (ReceiverJSON)getIntent().getSerializableExtra("receiver");
			consigneeText.setText(receiver.getConsignee());
			phoneText.setText(receiver.getPhone());
			addressText.setText(receiver.getAddress());
			zipCodeText.setText(receiver.getZipCode());
			receivernoneText.setVisibility(View.INVISIBLE);
			
			cartItemListJSON = cartItemService.getAll(this);
			for (CartItemJSON cartItemJSON : cartItemListJSON.getRecordList()) {
				total += cartItemJSON.getPrice().doubleValue()*cartItemJSON.getQuantity();
			}
		}
		totalText.setText(String.valueOf(total));
	}

	private void getdefaultReceiver() {
		if (NetUtils.isConnected(getApplicationContext())) {
			loadingDialog.show();
			new ReceiverAsyncTask().execute("");
		} else {
			Toast.makeText(getApplicationContext(), R.string.net_error, Toast.LENGTH_SHORT).show();
		}		
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.checkout_gohome:
			intent = new Intent(CheckoutActivity.this, MainActivity.class);
			intent.putExtra("referer", "CheckoutActivity");
			startActivity(intent);
			finish();
			break;
		
		case R.id.checkout_receiver_select:
			intent = new Intent(CheckoutActivity.this, ReceiverSelectActivity.class);
			intent.putExtra("referer", "CheckoutActivity");
			Bundle bundle = new Bundle();
			bundle.putSerializable("selectedReceiver", receiver);
			intent.putExtras(bundle);
			startActivity(intent);
			finish();
			break;
		
		case R.id.checkout_invoice:
			if (invoiceBox.isChecked()) {
				invoiceTitle.setVisibility(View.VISIBLE);
				invoiceText.setVisibility(View.VISIBLE);
			} else {
				invoiceTitle.setVisibility(View.INVISIBLE);
				invoiceText.setVisibility(View.INVISIBLE);
			}
			break;
		
		case R.id.checkout_submit:
			submitOrder(getApplicationContext(), v, referer, username, sign);
			break;
		
		default:
			break;
		}
	}
	
	private void submitOrder(Context context, View view, String referer, String username, String sign) {
		receiverId = (receiver != null) ? receiver.getReceiverId() : 0l;
		paymentMethodId = Long.valueOf(pmRadioGroup.getCheckedRadioButtonId());
		shippingMethodId = Long.valueOf(smRadioGroup.getCheckedRadioButtonId());
		invoiceinfo = invoiceText.getText().toString();
		if (receiverId.intValue() <= 0 ) {
			Toast.makeText(getApplicationContext(), R.string.checkout_check_error1, Toast.LENGTH_SHORT).show();
			return;
		}
		if (paymentMethodId <= 0 ) {
			Toast.makeText(getApplicationContext(), R.string.checkout_check_error2, Toast.LENGTH_SHORT).show();
			return;
		}
		if (shippingMethodId <= 0 ) {
			Toast.makeText(getApplicationContext(), R.string.checkout_check_error3, Toast.LENGTH_SHORT).show();
			return;
		}
		if (invoiceBox.isChecked() && (invoiceinfo == null || invoiceinfo.equals(""))) {
			Toast.makeText(getApplicationContext(), R.string.checkout_check_error4, Toast.LENGTH_SHORT).show();
			return;
		}
		if (invoiceBox.isChecked()) {
			isInvoice = true;
		}
		loadingDialog.show();
		new OrderSubmitAsyncTask().execute("");
	}

	@Override
	public void onBackPressed() {
		intent = new Intent(CheckoutActivity.this, MainActivity.class);
		intent.putExtra("referer", "CheckoutActivity");
		startActivity(intent);
		finish();
	}

	public class ReceiverAsyncTask extends AsyncTask<String, String, ReceiverJSON> {

		@Override
		protected ReceiverJSON doInBackground(String... params) {
			return new ReceiverService().getdefault(referer, username, sign);
		}

		@Override
		protected void onPostExecute(ReceiverJSON result) {
			if (result == null) {
				receivernoneText.setVisibility(View.VISIBLE);
				consigneePrefix.setVisibility(View.INVISIBLE);
				consigneeText.setVisibility(View.INVISIBLE);
				phonePrefix.setVisibility(View.INVISIBLE);
				phoneText.setVisibility(View.INVISIBLE);
				addressText.setVisibility(View.INVISIBLE);
				zipCodeText.setVisibility(View.INVISIBLE);
			} else {
				receiver = result;
				consigneeText.setText(result.getConsignee());
				phoneText.setText(result.getPhone());
				addressText.setText(result.getAddress());
				zipCodeText.setText(result.getZipCode());
				receivernoneText.setVisibility(View.INVISIBLE);
			}
			loadingDialog.dismiss();
		}
	}
	
	public class OrderSubmitAsyncTask extends AsyncTask<String, String, OrderJSON> {

		@Override
		protected OrderJSON doInBackground(String... params) {
			return orderService.submitOrder(getApplicationContext(), receiverId, paymentMethodId, shippingMethodId, isInvoice, invoiceinfo, referer, username, sign);
		}

		@Override
		protected void onPostExecute(OrderJSON result) {
			if (result != null) {
				Toast.makeText(getApplicationContext(), R.string.checkout_submit_success, Toast.LENGTH_SHORT).show();
				intent = new Intent(getApplicationContext(), PayActivity.class);
				intent.putExtra("referer", "CheckoutActivity");
				Bundle bundle = new Bundle();
				bundle.putSerializable("orderJSON", result);
				intent.putExtras(bundle);
				startActivity(intent);
				finish();
			} else {
				Toast.makeText(getApplicationContext(), R.string.checkout_check_error5, Toast.LENGTH_SHORT).show();
			}
			loadingDialog.dismiss();
		}
	}
}
